import React from 'react';
import { Card, Form, Select, DatePicker, Button, Space, Table, message } from 'antd';
import { AreaChartOutlined, BarChartOutlined } from '@ant-design/icons';
// 统一封装的 ECharts 引入（与其他统计页统一）
import echarts from '../../utils/echarts';
import dayjs from 'dayjs';

// 模仿 admin-web/src/views/statistics/DateProfit.vue
// 功能：指标卡片、日期范围选择（小时/天/月）、图表展示、表格与导出

const { RangePicker } = DatePicker;

const mockSeries = (() => {
  // 构造近 14 天的销量与销售额
  const days = Array.from({ length: 14 }).map((_, i) => {
    const d = dayjs().subtract(13 - i, 'day').format('YYYY-MM-DD');
    return d;
  });
  const num = days.map(() => Math.floor(100 + Math.random() * 400));
  const sales = days.map(() => parseFloat((2000 + Math.random() * 8000).toFixed(2)));
  return { days, num, sales };
})();

const initialTable = mockSeries.days.map((d, idx) => ({
  key: idx,
  orderDate: d,
  num: mockSeries.num[idx],
  sales: mockSeries.sales[idx],
}));
// 模拟广告统计数据（曝光、点击）
const initialAdData = mockSeries.days.map((d) => ({
  orderDate: d,
  impression: Math.floor(1000 + Math.random() * 4000),
  click: Math.floor(100 + Math.random() * 600),
}));

export default function DateProfit() {
  const [form] = Form.useForm();
  const chartRef = React.useRef(null);
  const chartInstance = React.useRef(null);
  const adChartRef = React.useRef(null);
  const adChartInstance = React.useRef(null);
  const [tableData, setTableData] = React.useState(initialTable);
  const [cards, setCards] = React.useState({
    todayNum: 0,
    todaySales: 0,
    num: 0,
    sales: 0,
  });

  const handleResize = React.useCallback(() => {
    chartInstance.current?.resize();
    adChartInstance.current?.resize();
  }, []);

  const updateCards = React.useCallback((data) => {
    const todayStr = dayjs().format('YYYY-MM-DD');
    const today = data.find((d) => d.orderDate === todayStr);
    const todayNum = today ? today.num : Math.floor(100 + Math.random() * 200);
    const todaySales = today ? today.sales : parseFloat((2000 + Math.random() * 3000).toFixed(2));
    const num = data.reduce((sum, cur) => sum + cur.num, 0);
    const sales = parseFloat(data.reduce((sum, cur) => sum + cur.sales, 0).toFixed(2));
    setCards({ todayNum, todaySales, num, sales });
  }, []);

  const renderChart = React.useCallback((data, searchType = 'num') => {
    const el = chartRef.current;
    if (!el) return;
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(el);
    }
    const xData = data.map((d) => d.orderDate);
    const yData = data.map((d) => (searchType === 'num' ? d.num : d.sales));
    chartInstance.current.setOption({
      tooltip: { trigger: 'axis' },
      grid: { left: 40, right: 40, top: 30, bottom: 40 },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [
        {
          type: searchType === 'num' ? 'bar' : 'line',
          data: yData,
          smooth: true,
          areaStyle: searchType === 'num' ? undefined : {},
          itemStyle: { color: '#1677ff' },
        },
      ],
    }, true);
    chartInstance.current.resize();
  }, []);

  // 广告统计折线图
  const renderAdChart = React.useCallback((data) => {
    const el = adChartRef.current;
    if (!el) return;
    if (!adChartInstance.current) {
      adChartInstance.current = echarts.init(el);
    }
    const xData = data.map((d) => d.orderDate);
    const impressionData = data.map((d) => d.impression);
    const clickData = data.map((d) => d.click);
    adChartInstance.current.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['曝光', '点击'] },
      grid: { left: 40, right: 40, top: 30, bottom: 40 },
      xAxis: { type: 'category', data: xData },
      yAxis: { type: 'value' },
      series: [
        {
          name: '曝光',
          type: 'line',
          smooth: true,
          data: impressionData,
          itemStyle: { color: '#52c41a' },
          areaStyle: {},
        },
        {
          name: '点击',
          type: 'line',
          smooth: true,
          data: clickData,
          itemStyle: { color: '#faad14' },
        },
      ],
    }, true);
    adChartInstance.current.resize();
  }, []);

  React.useEffect(() => {
    updateCards(tableData);
    renderChart(tableData, form.getFieldValue('searchType') || 'num');
    renderAdChart(initialAdData);
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
      chartInstance.current && chartInstance.current.dispose();
      adChartInstance.current && adChartInstance.current.dispose();
    };
  }, []); // eslint-disable-line

  const columns = [
    { title: '日期', dataIndex: 'orderDate', key: 'orderDate' },
    { title: '销量', dataIndex: 'num', key: 'num', width: 130, align: 'right' },
    {
      title: '销售额',
      dataIndex: 'sales',
      key: 'sales',
      width: 130,
      align: 'right',
      render: (v) => `$${v.toLocaleString()}`,
    },
  ];

  const onSearch = () => {
    const { dayType, dateRange, searchType } = form.getFieldsValue();
    // 根据 dayType 模拟筛选区间
    let filtered = initialTable;
    let adFiltered = initialAdData;
    if (dateRange && dateRange.length === 2) {
      const start = dayjs(dateRange[0]);
      const end = dayjs(dateRange[1]);
      filtered = initialTable.filter((d) => {
        const cur = dayjs(d.orderDate, 'YYYY-MM-DD');
        return cur.isAfter(start.subtract(1, 'day')) && cur.isBefore(end.add(1, 'day'));
      });
      adFiltered = initialAdData.filter((d) => {
        const cur = dayjs(d.orderDate, 'YYYY-MM-DD');
        return cur.isAfter(start.subtract(1, 'day')) && cur.isBefore(end.add(1, 'day'));
      });
    }
    setTableData(filtered);
    updateCards(filtered);
    renderChart(filtered, searchType || 'num');
    renderAdChart(adFiltered);
  };

  const onReset = () => {
    form.resetFields();
    setTableData(initialTable);
    updateCards(initialTable);
    renderChart(initialTable, 'num');
    renderAdChart(initialAdData);
  };

  const exportCSV = () => {
    const header = ['日期', '销量', '销售额'];
    const rows = tableData.map((r) => [r.orderDate, r.num, r.sales]);
    const csv = [header, ...rows].map((row) => row.join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `date-profit-${dayjs().format('YYYYMMDDHHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
    message.success('导出成功');
  };

  return (
    <div>
      <div style={{ width: 1670, padding: '20px 15px', display: 'flex', alignItems: 'center' }}>
        <Card style={{ marginRight: 7.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 420 }}>
            <div style={{ width: '50%', fontSize: 13, color: '#909399' }}>
              <div>今日销量</div>
              <div style={{ fontSize: 28, textAlign: 'center', color: '#1677ff', fontWeight: 'bold' }}>{cards.todayNum}</div>
            </div>
            <div style={{ width: '50%', fontSize: 13, color: '#909399' }}>
              <div>今日销售额</div>
              <div style={{ fontSize: 28, textAlign: 'center', color: '#1677ff', fontWeight: 'bold' }}>{`$${cards.todaySales.toLocaleString()}`}</div>
            </div>
          </div>
        </Card>
        <Card style={{ marginLeft: 7.5 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', width: 420 }}>
            <div style={{ width: '50%', fontSize: 13, color: '#909399' }}>
              <div>总销量</div>
              <div style={{ fontSize: 28, textAlign: 'center', color: '#1677ff', fontWeight: 'bold' }}>{cards.num.toLocaleString()}</div>
            </div>
            <div style={{ width: '50%', fontSize: 13, color: '#909399' }}>
              <div>总销售额</div>
              <div style={{ fontSize: 28, textAlign: 'center', color: '#1677ff', fontWeight: 'bold' }}>{`$${cards.sales.toLocaleString()}`}</div>
            </div>
          </div>
        </Card>
      </div>

      <div
        style={{
          width: 1638,
          margin: '0 15px 15px 15px',
          padding: 15,
          backgroundColor: '#f3f3f3',
          display: 'flow-root',
          border: '1px solid #e7e7e7',
          borderRadius: 3,
        }}
      >
        <div style={{ lineHeight: '32px', width: 200, height: 30, fontSize: 15, display: 'flex', alignItems: 'center', gap: 8 }}>
          <AreaChartOutlined style={{ color: '#1677ff', fontSize: 18 }} />
          <span>日益统计</span>
        </div>
        <div style={{ width: 1400 }}>
          <div style={{ width: '100%', display: 'flow-root' }}>
            <Button type="primary" onClick={exportCSV} size="small" style={{ marginRight: 15 }}>
              导出
            </Button>
            <Form form={form} layout="inline" initialValues={{ searchType: 'num', dayType: '2' }}>
              <Form.Item label="统计类型" name="searchType">
                <Select size="small" style={{ width: 170 }}>
                  <Select.Option value="num">销量</Select.Option>
                  <Select.Option value="sales">销售额</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="统计周期" name="dayType">
                <Select size="small" style={{ width: 170 }}>
                  <Select.Option value="1">按小时</Select.Option>
                  <Select.Option value="2">按天</Select.Option>
                  <Select.Option value="3">按月</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item label="日期范围" name="dateRange">
                <RangePicker
                  size="small"
                  style={{ width: 335 }}
                  allowClear
                  format={(form.getFieldValue('dayType') || '2') === '1' ? 'YYYY-MM-DD HH:mm:ss' : (form.getFieldValue('dayType') || '2') === '2' ? 'YYYY-MM-DD' : 'YYYY-MM'}
                  showTime={(form.getFieldValue('dayType') || '2') === '1'}
                  picker={(form.getFieldValue('dayType') || '2') === '3' ? 'month' : 'date'}
                />
              </Form.Item>
              <Form.Item>
                <Space>
                  <Button type="primary" size="small" onClick={onSearch}>
                    搜索
                  </Button>
                  <Button size="small" onClick={onReset}>重置</Button>
                </Space>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>

      <div style={{ width: 1670, padding: 15, display: 'flow-root' }}>
        <div id="rytjchart" ref={chartRef} style={{ width: 1670, height: 400 }} />
      </div>

      <div
        style={{
          width: 1638,
          margin: '0 15px 0 15px',
          padding: 15,
          backgroundColor: '#f3f3f3',
          display: 'flow-root',
          border: '1px solid #e7e7e7',
          borderRadius: 3,
        }}
      >
        <div style={{ lineHeight: '32px', width: 200, height: 30, fontSize: 15, display: 'flex', alignItems: 'center', gap: 8 }}>
          <BarChartOutlined style={{ color: '#52c41a', fontSize: 18 }} />
          <span>广告统计</span>
          <span style={{ marginLeft: 6, fontSize: 12, color: '#909399' }}>折线图</span>
        </div>
      </div>

      <div style={{ width: 1670, padding: 15, display: 'flow-root' }}>
        <div id="adverchart" ref={adChartRef} style={{ width: 1670, height: 400 }} />
      </div>

      <div className="vue-padding radius">
        <Table
          dataSource={tableData}
          columns={columns}
          pagination={{ pageSize: 10 }}
          summary={(pageData) => {
            const totalNum = pageData.reduce((sum, cur) => sum + cur.num, 0);
            const totalSales = pageData.reduce((sum, cur) => sum + cur.sales, 0);
            return (
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
                <Table.Summary.Cell index={1} align="right">{totalNum.toLocaleString()}</Table.Summary.Cell>
                <Table.Summary.Cell index={2} align="right">${totalSales.toLocaleString()}</Table.Summary.Cell>
              </Table.Summary.Row>
            );
          }}
        />
      </div>
    </div>
  );
}